package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //在Controller运行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 从session中获取员工id，判断用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        //2. 员工登录
        if (empId != null) {
            //将员工的id存入当前线程
            BaseContext.set(empId);
            return true;
        }


        Long userId = (Long) request.getSession().getAttribute("user");
        //2. 员工登录
        if (userId != null) {
            //将user的id存入当前线程
            BaseContext.set(userId);
            return true;
        }


        //3. 说明员工未登录，响应数据给前端 code=0 msg=NOTLOGIN
        R r = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(r));
        return false;
    }

}
